﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace LdCms.Web.Controllers.MVC.Community
{
    using LdCms.EF.DbModels;
    using LdCms.Model.Community;
    using LdCms.IBLL.Community;
    using LdCms.IBLL.Member;
    using LdCms.Common.Extension;
    using LdCms.Common.Utility;
    using LdCms.Common.Web;
    using LdCms.Common.Json;
    using LdCms.Common.Enum;
    using LdCms.Web.Models;
    using LdCms.Web.Services;
    using LdCms.Common.Security;
    using LdCms.Web.Authorizes;
    /// <summary>
    /// 
    /// </summary>
    [AdminAuthorizeAttribute(Roles = "Admins")]
    public class CommunityColumnController : BaseController
    {
        private readonly IBaseManager BaseManager;
        private readonly IRankService RankService;
        private readonly IColumnService ColumnService;
        private readonly IColumnPermissionService ColumnPermissionService;
        public CommunityColumnController(IBaseManager BaseManager, IRankService RankService, IColumnService ColumnService, IColumnPermissionService ColumnPermissionService) : base(BaseManager)
        {
            this.BaseManager = BaseManager;
            this.RankService = RankService;
            this.ColumnService = ColumnService;
            this.ColumnPermissionService = ColumnPermissionService;
        }
        public override IActionResult Index()
        {
            return View();
        }

        public IActionResult List()
        {
            try
            {
                string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.扩展管理.友情链接.列表);
                if (!IsPermission(funcId)) { return ToPermission(funcId); }
                var lists = ColumnService.GetColumnAll(SystemID, CompanyID);
                ViewData["Count"] = ColumnService.CountColumn(SystemID, CompanyID);
                return View(lists);
            }
            catch (Exception ex)
            {
                return ToError(ex.Message);
            }
        }
        public IActionResult Add(string columnId)
        {
            try
            {
                #region 专栏权限
                ViewData["IsShow"] = GetColumnPermissionMemberRank(columnId, (int)ParamEnum.ColumnPermission.查看权限);
                ViewData["IsSend"] = GetColumnPermissionMemberRank(columnId, (int)ParamEnum.ColumnPermission.发帖权限);
                ViewData["IsReply"] = GetColumnPermissionMemberRank(columnId, (int)ParamEnum.ColumnPermission.回帖权限);
                #endregion

                if (string.IsNullOrWhiteSpace(columnId))
                    return View(new Ld_Community_Column());
                var entity = ColumnService.GetColumn(SystemID, CompanyID, columnId);
                if (entity == null)
                    return View(new Ld_Community_Column());
                return View(entity);
            }
            catch (Exception ex)
            {
                return ToError(ex.Message);
            }
        }
        public JsonResult Save(string columnId)
        {
            try
            {
                string fColumnName = GetFormValue("fColumnName");
                string fImgSrc = GetFormValue("fImgSrc");
                string fIsShow = GetFormValueArr("fIsShow");
                string fIsSend = GetFormValueArr("fIsSend");
                string IsReply = GetFormValueArr("IsReply");
                string fTitle = GetFormValue("fTitle");
                string fKeyword = GetFormValue("fKeyword");
                string fDescription = GetFormValue("fDescription");
                string fSort = GetFormValue("fSort");
                string fIsLock = GetFormValue("fIsLock");
                string fState = GetFormValue("fState");

                var communityColumn = PrimaryKeyHelper.PrimaryKeyType.CommunityColumn;
                var primaryKeyLen = PrimaryKeyHelper.PrimaryKeyLen.V1;
                string createColumnId = PrimaryKeyHelper.MakePrimaryKey(communityColumn, primaryKeyLen);
                string fColumnId = string.IsNullOrEmpty(columnId) ? createColumnId : columnId;
                List<Ld_Member_Rank> listMemberRank = GetMemberRankAll();

                Ld_Community_Column entity = new Ld_Community_Column();
                List<Ld_Community_ColumnPermission> lists = new List<Ld_Community_ColumnPermission>();
                entity.SystemID = SystemID;
                entity.CompanyID = CompanyID;
                entity.ColumnID = fColumnId;
                entity.ColumnName = fColumnName;
                entity.ImgSrc = fImgSrc;
                entity.Title = fTitle;
                entity.Keyword = fKeyword;
                entity.Description = fDescription;
                entity.Sort = Utility.IsNum(fSort, 0);
                entity.IsLock = fIsLock.ToBool();
                entity.State = fState.ToBool();
                if (!string.IsNullOrEmpty(fIsShow))
                {
                    foreach (var m in fIsShow.Split(","))
                    {
                        lists.Add(new Ld_Community_ColumnPermission()
                        {
                            TypeID = (int)ParamEnum.ColumnPermission.查看权限,
                            TypeName = ParamEnum.ColumnPermission.查看权限.ToString(),
                            RankID = m,
                            RankName = listMemberRank.Where(x => x.RankID == m).FirstOrDefault().RankName,
                            State = true
                        });
                    }
                }
                if (!string.IsNullOrEmpty(fIsSend))
                {
                    foreach (var m in fIsSend.Split(","))
                    {
                        lists.Add(new Ld_Community_ColumnPermission()
                        {
                            TypeID = (int)ParamEnum.ColumnPermission.发帖权限,
                            TypeName = ParamEnum.ColumnPermission.发帖权限.ToString(),
                            RankID = m,
                            RankName = listMemberRank.Where(x => x.RankID == m).FirstOrDefault().RankName,
                            State = true
                        });
                    }
                }
                if (!string.IsNullOrEmpty(IsReply))
                {
                    foreach (var m in IsReply.Split(","))
                    {
                        lists.Add(new Ld_Community_ColumnPermission()
                        {
                            TypeID = (int)ParamEnum.ColumnPermission.回帖权限,
                            TypeName = ParamEnum.ColumnPermission.回帖权限.ToString(),
                            RankID = m,
                            RankName = listMemberRank.Where(x => x.RankID == m).FirstOrDefault().RankName,
                            State = true
                        });
                    }
                }
                bool result = false;
                if (string.IsNullOrEmpty(columnId))
                    result = ColumnService.SaveColumn(entity, lists);
                else
                    result = ColumnService.UpdateColumn(entity, lists);
                if (result)
                    return Success("ok");
                else
                    return Error("fail");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        [HttpPost]
        public JsonResult UpdateState(string columnId, bool state)
        {
            try
            {
                string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.栏目管理.栏目分类.审核);
                if (!IsPermission(funcId)) { return Error("您没有操作权限，请联系系统管理员！"); }
                var result = ColumnService.UpdateColumnState(SystemID, CompanyID, columnId, state);
                if (result)
                    return Success("ok");
                else
                    return Error("fail");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }
        [HttpPost]
        public JsonResult Delete(string columnId)
        {
            try
            {
                string funcId = PermissionEnum.CodeFormat((int)PermissionEnum.栏目管理.栏目分类.删除);
                if (!IsPermission(funcId)) { return Error("您没有操作权限，请联系系统管理员！"); }

                var result = ColumnService.DeleteColumn(SystemID, CompanyID, columnId);
                if (result)
                    return Success("ok");
                else
                    return Error("fail");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        [ActionName("member-rank-all")]
        public JsonResult GetMemberRank(string columnId, int typeId)
        {
            try
            {
                var data = GetColumnPermissionMemberRank(columnId, typeId);
                return Success("ok", data);
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }


        private List<ColumnPermissionMemberRank> GetColumnPermissionMemberRank(string columnId, int typeId)
        {
            try
            {
                var listsMemberRank = RankService.GetRankStatePro(SystemID, CompanyID, true.ToString());
                var listsColumnPermission = ColumnPermissionService.GetColumnPermissionByColumnId(SystemID, CompanyID, columnId, typeId);
                var data = from m in listsMemberRank
                           join x in listsColumnPermission on new { m.SystemID, m.CompanyID, m.RankID } equals new { x.SystemID, x.CompanyID, x.RankID }
                           into mx
                           from c in mx.DefaultIfEmpty()
                           select new
                           {
                               ID = m.RankID,
                               Name = m.RankName,
                               Selected = c == null ? false : true
                           };
                return data.ToJson().ToList<ColumnPermissionMemberRank>();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        private List<Ld_Member_Rank> GetMemberRankAll()
        {
            try
            {
                return RankService.GetRankStatePro(SystemID, CompanyID, true.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

    }
}